package com.istock.union.controller.vue;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.istock.base.common.api.model.ApiBaseResponse;
import com.istock.base.common.api.model.RetStatusEnum;
import com.istock.union.model.MenuItemVo;
import com.istock.union.user.client.SSOClientUtils;
import com.istock.union.user.model.Constants;
import com.istock.union.user.model.MenuInfo;
import com.istock.union.user.model.OperLog;
import com.istock.union.user.model.SSOUser;
import com.istock.union.user.model.UpdatePasswordModel;
import com.istock.union.user.model.UserInfo;
import com.istock.union.user.service.MenuInfoService;
import com.istock.union.user.service.UserInfoService;

@Controller
@RequestMapping("/s/vue")
public class VuePermissionController {

	@Autowired
	private MenuInfoService menuInfoService;
	@Autowired
	private UserInfoService userInfoService;
	
	@Value("${sso.login.verifyCount:3}")
	private Integer overVerifyCount;
	
	@RequestMapping("findUserInfo")
	@ResponseBody
	public ApiBaseResponse<SSOUser> findUserInfo(){
		//SSOUser user = SSOClientUtils.getInstance().findCurrentUser();
		return new ApiBaseResponse<>(RetStatusEnum.SUCCESS,Constants.API_RESPONSE_SUCCESS_CODE,Constants.API_RESPONSE_SUCCESS_MESSAGE ,SSOClientUtils.getInstance().findCurrentUser());
	}
	
	@RequestMapping("checkPermissions")
    @ResponseBody
    public ApiBaseResponse<Map<String,Boolean>> checkPermissions(String[] permissions){
        SSOUser ssoUser = SSOClientUtils.getInstance().findCurrentUser();

        Map<String,Boolean> result = new HashMap<>();
        if (SSOClientUtils.getInstance().isAdmin()) {
            for(String permission:permissions){
                result.put(permission,Boolean.TRUE);
            }
            return new ApiBaseResponse<>(RetStatusEnum.SUCCESS,Constants.API_RESPONSE_SUCCESS_CODE, 
                    Constants.API_RESPONSE_SUCCESS_MESSAGE, result);
        }

        for(String permission:permissions){
                result.put(permission,ssoUser.getPermissions().contains(permission));
            }
            return new ApiBaseResponse<>(RetStatusEnum.SUCCESS,Constants.API_RESPONSE_SUCCESS_CODE, 
                    Constants.API_RESPONSE_SUCCESS_MESSAGE, result);
    }


    @RequestMapping("setPwd")
    @ResponseBody
    @OperLog(functionName = "authority.menu.userInfo.setPassword", menuName = "authority.menu.userInfo")
    public ApiBaseResponse<Object> setPwd(UpdatePasswordModel updateUser) {
        SSOUser user = SSOClientUtils.getInstance().findCurrentUser();
        if (null == user) {
            return new ApiBaseResponse<Object>(
                    RetStatusEnum.FAIL, "NOLOGIN","no login", null);
        }

        if (StringUtils.isBlank(updateUser.getNewPassword())
                || StringUtils.isBlank(updateUser.getConfirmNewPassword())) {
            return new ApiBaseResponse<Object>(RetStatusEnum.FAIL,Constants.API_RESPONSE_FAIL_CODE, "新密码不能为空" , null);
        }
        
        ApiBaseResponse<UserInfo> checkResult = userInfoService.checkUserPasswd(user.getUserId(), updateUser.getOldPassword());
        if(checkResult.getStatus() != RetStatusEnum.SUCCESS) {
        	return new ApiBaseResponse<Object>(RetStatusEnum.FAIL,Constants.API_RESPONSE_FAIL_CODE, "旧密码不正确" , null);
        }

        userInfoService.changePassword(user.getUserId(), updateUser.getConfirmNewPassword());
        return new ApiBaseResponse<Object>(RetStatusEnum.SUCCESS,Constants.API_RESPONSE_FAIL_CODE, "修改密码成功" , null);
    }

        @RequestMapping("/indexMenu")
    @ResponseBody
    public ApiBaseResponse<List<MenuItemVo>> indexMenu() {
        SSOUser ssoUser = SSOClientUtils.getInstance().findCurrentUser();
        List<MenuInfo> menuList;
        if (SSOClientUtils.getInstance().isAdmin()) {
            menuList = menuInfoService.findAllMenu();
        } else {
        	//TODO 使用当前的身份ID
            menuList = menuInfoService.findMenuInfoByCredentialId(ssoUser.getCredentialId());
        }

        List<MenuInfo> rootMenuInfoList = findNodeList(menuList, "0");

        List<MenuItemVo> result = new ArrayList<MenuItemVo>();
        for (MenuInfo item : rootMenuInfoList) {
            MenuItemVo voItem = toMenuItemVo(item,menuList);
            result.add(voItem);
        }

        return new ApiBaseResponse<>(RetStatusEnum.SUCCESS,Constants.API_RESPONSE_SUCCESS_CODE, 
                Constants.API_RESPONSE_SUCCESS_MESSAGE, result);
    }

    private MenuItemVo toMenuItemVo(MenuInfo menuInfo, List<MenuInfo> source) {
        MenuItemVo menuItemVo = new MenuItemVo();

        menuItemVo.setPath(menuInfo.getVuePath());
        menuItemVo.setHidden(!menuInfo.getVisible().equals(1));
        menuItemVo.setComponent(menuInfo.getVueComponent());
        menuItemVo.setIndex(menuInfo.getOrderNum());
        menuItemVo.getMeta().setTitle(menuInfo.getMenuName());
        menuItemVo.getMeta().setIcon(menuInfo.getIcon());

        List<MenuInfo> childMenuInfoList = findNodeList(source,menuInfo.getId());
        List<MenuItemVo> childMenuItemVoList = new ArrayList<>();
        for(MenuInfo item:childMenuInfoList){
            MenuItemVo result =toMenuItemVo(item,source);
            childMenuItemVoList.add(result);
        }
        menuItemVo.setChildren(childMenuItemVoList);

        return menuItemVo;
    }

    private List<MenuInfo> findNodeList(List<MenuInfo> source, String parentId) {
        List<MenuInfo> result = new ArrayList<>();
        for (MenuInfo item : source) {
            if (item.getParentId().equals(parentId)) {
                result.add(item);
            }
        }
        return result;
    }
	
}
